import { getSongs, getLyric, getSongUrl } from '../api'
export default {
  setFullScreen ({ commit }, flag) {
    commit('changeFullScreen', flag)
  },
  setminiplay ({ commit }, flag) {
    commit('setMiniplay', flag)
  },
  setplay ({ commit }, flag) {
    commit('setPlay', flag)
  },
  setMode ({ commit }, flag) {
    commit('setMode', flag)
  },
  isshowList ({ commit }, flag) {
    commit('isShowList', flag)
  },
  async setsongs ({ commit }, ids) {
    const result = await getSongs({ ids: ids.join(',') })
    const urls = await getSongUrl({ id: ids.join(',') })
    // console.log(urls)
    const list = []
    result.songs.map(function (value, i) {
      const obj = {}
      obj.name = value.name
      // obj.url = urls.data[i].url
      for (let j = 0; j < urls.data.length; j++) {
        if (value.id === urls.data[j].id) {
          obj.url = urls.data[j].url
          break
        }
      }
      let singer = ''
      value.ar.map(function (item, index) {
        if (index === 0) {
          singer = item.name
        } else {
          singer += '-' + item.name
        }
      })
      obj.singer = singer
      obj.picUrl = value.al.picUrl
      obj.id = value.id
      list.push(obj)
    })
    commit('setsongs', list)
  },
  async getLyric ({ commit }, id) {
    const result = await getLyric({ id: id })
    const obj = parseLyric(result.lrc.lyric)
    commit('setlyric', obj)
  },
  setdel ({ commit }, index) {
    commit('setdel', index)
  },
  setIndexs ({ commit }, index) {
    commit('setIndex', index)
  },
  setCurrentTimes ({ commit }, time) {
    commit('setCurrentTime', time)
  },
  setFavoriteSong ({ commit }, song) {
    commit('setFavoriteSong', song)
  },
  setFavoriteList ({ commit }, list) {
    commit('FavoriteList', list)
  },
  sethistorySong ({ commit }, song) {
    commit('sethistorySong', song)
  },
  sethistoryList ({ commit }, list) {
    commit('sethistoryList', list)
  }
}
// 格式化歌词方法
function parseLyric (lrc) {
  const lyrics = lrc.split('\n')
  // [00:00.000] 作曲 : 林俊杰
  // 1.定义正则表达式提取[00:00.000]
  const reg1 = /\[\d*:\d*\.\d*\]/g
  // 2.定义正则表达式提取 [00
  const reg2 = /\[\d*/i
  // 3.定义正则表达式提取 :00
  const reg3 = /\:\d*/i
  // 4.定义对象保存处理好的歌词
  const lyricObj = {}
  lyrics.forEach(function (lyric) {
    // 1.提取时间
    let timeStr = lyric.match(reg1)
    if (!timeStr) { return }
    timeStr = timeStr[0]
    // 2.提取分钟
    const minStr = timeStr.match(reg2)[0].substr(1)
    // 3.提取秒钟
    const secondStr = timeStr.match(reg3)[0].substr(1)
    // 4.合并时间, 将分钟和秒钟都合并为秒钟
    const time = parseInt(minStr) * 60 + parseInt(secondStr)
    // 5.处理歌词
    const text = lyric.replace(reg1, '').trim()
    // 6.保存数据
    lyricObj[time] = text
  })
  return lyricObj
}
